﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Domain.ScGetWMSTaskDomain;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.WMSApiDomain.WebApi;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.ScMessage
{
    /// <summary>
    /// 无用可删
    /// </summary>
    public class QTScActionMessageService : IScActionMessageService
    {
        private readonly IPlcConnectionPoolService _plcConnectionPoolService;
        private readonly ILogUtil _logUtil;
        //private readonly IScMessageServiceFactory _scMessageServiceFactory;
        private readonly IScGetWMSTaskService _scGetWMSTaskService;
        private readonly ISnowflake _Snowflake;
        private readonly ITelegramRecordInfoRepository _TelegramRecordInfoRepository;

        public QTScActionMessageService(IPlcConnectionPoolService plcConnectionPoolService,
            ILogUtil logUtil,
            //IScMessageServiceFactory scMessageServiceFactory,
            IScGetWMSTaskService scGetWMSTaskService,
            ISnowflake snowflake,
            ITelegramRecordInfoRepository telegramRecordInfoRepository)
        {
            _plcConnectionPoolService = plcConnectionPoolService;
            _logUtil = logUtil;
            //_scMessageServiceFactory = scMessageServiceFactory;
            _scGetWMSTaskService = scGetWMSTaskService;

            _Snowflake = snowflake;
            _TelegramRecordInfoRepository = telegramRecordInfoRepository;
        }
        public async Task ProcessActionMessageAsync(EquipmentDbObject scEquipmentDbObject, List<EquipmentDbObject> puDoEquipmentDbObjects)
        {
            //1、SC动作报文

            //if (!(scEquipmentDbObject != null && scEquipmentDbObject.bytesObjectBases != null && scEquipmentDbObject.bytesObjectBases.Count > 0))
            //{
            //    return;
            //    throw new Exception($"SC编号:{scEquipmentDbObject.EquipmentCode} 报文异常");
            //}

            //if (!(puDoEquipmentDbObjects != null && puDoEquipmentDbObjects.Count > 0))
            //{
            //    throw new Exception($"SC编号:{scEquipmentDbObject.EquipmentCode} 交接台报文异常");
            //}

            if (scEquipmentDbObject == null)
            {
                return;
                throw new Exception($"SC编号:{scEquipmentDbObject.EquipmentCode} 报文异常");
            }

            var plcActionMessages = scEquipmentDbObject.bytesObjectBases.Find(o => o.ObjectType.Contains("PlcActionBO"));
            QTScMessagePlcActionBO qTScMessagePlcActionBO = plcActionMessages as QTScMessagePlcActionBO;
            var wcsActionMessages = scEquipmentDbObject.bytesObjectBases.Find(o => o.ObjectType.Contains("WcsActionBO"));
            QTScMessageWcsActionBO qTScMessageWcsActionBO = wcsActionMessages as QTScMessageWcsActionBO;

            //添加报文记录
            var telegramUniqueIDObj = new { PLC = GenerateMD5.CreateMD5(JsonConvert.SerializeObject(qTScMessagePlcActionBO)), WCS = GenerateMD5.CreateMD5(JsonConvert.SerializeObject(qTScMessageWcsActionBO)) };
            var telegramUniqueIDJson = JsonConvert.SerializeObject(telegramUniqueIDObj);
            var telgramRecord = await _TelegramRecordInfoRepository.GetFirstAsync(it => it.TelegramUniqueIDJson == telegramUniqueIDJson);
            if (telgramRecord == null || telgramRecord.ID <= 0)
            {
                var telegramRecordInfo = new TelegramRecordInfo()
                {
                    ID = _Snowflake.GetId(),
                    EquipmentCode = qTScMessagePlcActionBO.EquipmentCode,
                    TelegramUniqueIDJson = telegramUniqueIDJson,
                    PlcTelegramJson = JsonConvert.SerializeObject(qTScMessagePlcActionBO),
                    WcsTelegramJson = JsonConvert.SerializeObject(qTScMessageWcsActionBO),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };
                await _TelegramRecordInfoRepository.InsertAsync(telegramRecordInfo);
            }
            else
            {
                telgramRecord.UpdateTime = DateTime.Now;
                await _TelegramRecordInfoRepository.UpdateAsync(telgramRecord);
            }

            //2、交接台状态报文
            List<PlanarStateBO> planarStateBOs = new List<PlanarStateBO>();
            if (puDoEquipmentDbObjects != null && scEquipmentDbObject.bytesObjectBases != null && scEquipmentDbObject.bytesObjectBases.Count > 0)
            {
                foreach (var temp in puDoEquipmentDbObjects)
                {
                    var stateMessages = temp.bytesObjectBases.Find(o => o.ObjectType.Contains("StateBO"));
                    PlanarStateBO planarStateBO = stateMessages as PlanarStateBO;
                    planarStateBOs.Add(planarStateBO);
                }
            }


            if (qTScMessageWcsActionBO != null && qTScMessagePlcActionBO != null)
            {

                #region  SC卸载报完成
                if (qTScMessagePlcActionBO.OperationMode == 2 &&
                    qTScMessagePlcActionBO.ProcessState == 5 &&
                    qTScMessageWcsActionBO.CompletionFlag == 0)
                {
                    try
                    {
                        var wmstask = await _scGetWMSTaskService.ScGetWorkTaskInfoByWcsTaskCodeAsync(qTScMessagePlcActionBO.ExecutedJobNum);
                        if (wmstask != null)
                        {
                            //throw new Exception($"SC编号{qTScMessagePlcActionBO.EquipmentCode} 作业号{qTScMessagePlcActionBO.ExecutedJobNum} 没有WCS作业");

                            var routedetail = await _scGetWMSTaskService.GetRouteDetailInfoByIdAsync(wmstask.CurrentRounteDetailID);
                            //byte[] wcsBytes = new byte[1];
                            //HelperByte.SetIntAt(wcsBytes, 34, 2);
                            ////Sc写入Db
                            //PlcWriteDbInfo plcWriteDbInfo = await _scGetWMSTaskService.ScGetPlcWriteDbInfoAsync(qTScMessagePlcActionBO.EquipmentCode, "QTScMessageWriteWcsActionBO");
                            ////Sc使用Plc连接
                            //var plcservice = _plcConnectionPoolService.S7GetWritePlcConnection(plcWriteDbInfo.PlcConnectionId);
                            //if (plcservice == null)
                            //{
                            //    throw new Exception($"PLC连接Id:{plcWriteDbInfo.PlcConnectionId}不存在");
                            //}
                            if (routedetail.IsEnd)
                            {
                                //bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart + 34, wcsBytes);
                                {
                                    wmstask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                                    wmstask.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                                    wmstask.CurrentUpdateTime = DateTime.Now;
                                    wmstask.TaskState = EnumTaskState.Finish;
                                    wmstask.UpdateTime = DateTime.Now;
                                    WMSApiDomain.WebApi.HeaderResult<bool> send = new();
                                    try
                                    {
                                        send = await WCSMessageWithWMSApi.WCSNoticeTaskAutoCompleteAsync(wmstask.WmsTaskCode,wmstask.PalletCode,wmstask.WmsToPosition);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logUtil.Info($"{wmstask.WmsTaskCode} 上报WMS消息异常," + ex.ToString());
                                    }
                                    if (send.IsSucceed)
                                    {
                                        wmstask.UploadWmsState = EnumUploadWmsState.Succeed;
                                    }
                                    else
                                    {
                                        wmstask.UploadWmsState = EnumUploadWmsState.Failed;
                                    }
                                    wmstask.UploadWmsTime = DateTime.Now;
                                    await _scGetWMSTaskService.ScUpdateWorkTaskInfoAsync(wmstask);

                                    TaskRouteDetailRecordInfo taskRouteDetailRecordInfo = new TaskRouteDetailRecordInfo();
                                    taskRouteDetailRecordInfo.TaskID = wmstask.ID;
                                    taskRouteDetailRecordInfo.RouteDetailID = wmstask.CurrentRounteDetailID;
                                    taskRouteDetailRecordInfo.DetailTaskState = EnumDetailTaskState.Finish;
                                    taskRouteDetailRecordInfo.DispatchType = wmstask.CurrentDispatchType;
                                    taskRouteDetailRecordInfo.FromEquipment = wmstask.CurrentFromEquipment;
                                    taskRouteDetailRecordInfo.FromCargo = wmstask.CurrentFromCargo;
                                    taskRouteDetailRecordInfo.ToEquipment = wmstask.CurrentToEquipment;
                                    taskRouteDetailRecordInfo.ToCargo = wmstask.CurrentToCargo;
                                    taskRouteDetailRecordInfo.CreateTime = wmstask.CurrentCreateTime;
                                    taskRouteDetailRecordInfo.UpdateTime = DateTime.Now;
                                    await _scGetWMSTaskService.InsertTaskRouteDetailRecordInfoAsync(taskRouteDetailRecordInfo);
                                }
                            }
                            else
                            {
                                TaskRouteDetailRecordInfo taskRouteDetailRecordInfo = new TaskRouteDetailRecordInfo();
                                taskRouteDetailRecordInfo.TaskID = wmstask.ID;
                                taskRouteDetailRecordInfo.RouteDetailID = routedetail.ID;
                                taskRouteDetailRecordInfo.DetailTaskState = EnumDetailTaskState.Finish;
                                taskRouteDetailRecordInfo.DispatchType = routedetail.DispatchType;
                                taskRouteDetailRecordInfo.FromEquipment = routedetail.FromEquipment;
                                taskRouteDetailRecordInfo.FromCargo = routedetail.FromCargo;
                                taskRouteDetailRecordInfo.ToEquipment = routedetail.ToEquipment;
                                taskRouteDetailRecordInfo.ToCargo = routedetail.ToCargo;
                                taskRouteDetailRecordInfo.CreateTime = wmstask.CurrentCreateTime;
                                taskRouteDetailRecordInfo.UpdateTime = DateTime.Now;

                                var nextroutedetail = await _scGetWMSTaskService.GetNextRouteDetailInfoByIdAsync(wmstask.CurrentRounteDetailID);
                                wmstask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                                wmstask.CurrentRounteDetailID = nextroutedetail.ID;
                                wmstask.CurrentDetailTaskState = EnumDetailTaskState.Init;
                                wmstask.CurrentDispatchType = nextroutedetail.DispatchType;
                                wmstask.CurrentFromEquipment = nextroutedetail.FromEquipment;
                                wmstask.CurrentFromCargo = nextroutedetail.FromCargo;
                                wmstask.CurrentToEquipment = nextroutedetail.ToEquipment;
                                wmstask.CurrentToCargo = nextroutedetail.ToCargo;
                                wmstask.CurrentCreateTime = DateTime.Now;
                                wmstask.CurrentUpdateTime = new DateTime(1900, 1, 1);

                                //bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart + 34, wcsBytes);
                                {
                                    await _scGetWMSTaskService.ScUpdateWorkTaskInfoRouteDetailAsync(wmstask);
                                    if (wmstask.TaskType == EnumTaskType.ATS || wmstask.TaskType == EnumTaskType.ATA)
                                    {
                                        if (routedetail.IsStart)
                                            await WCSMessageWithWMSApi.WCSNoticePalltetArriveDoEquipmentAsync(wmstask.WmsTaskCode);
                                    }
                                    await _scGetWMSTaskService.InsertTaskRouteDetailRecordInfoAsync(taskRouteDetailRecordInfo);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logUtil.Info(ex.ToString());
                    }
                }
                #endregion

                #region  SC执行空闲的作业
                if (qTScMessagePlcActionBO.OperationMode == 2 &&
                    qTScMessagePlcActionBO.EquipmentStatus == 2 &&
                    qTScMessagePlcActionBO.FaultCode == 0 &&
                    qTScMessagePlcActionBO.Fork1Status == 0 &&
                    (qTScMessagePlcActionBO.ProcessState == 0 || qTScMessagePlcActionBO.ProcessState == 5) &&
                    qTScMessageWcsActionBO.CompletionFlag == 0)
                {
                    try
                    {
                        if (qTScMessagePlcActionBO.ProcessState == 5)
                        {
                            var Existwmstask = await _scGetWMSTaskService.ScGetWorkTaskInfoByWcsTaskCodeAsync(qTScMessagePlcActionBO.ExecutedJobNum);
                            if (Existwmstask != null)
                            {
                                //
                                _logUtil.Info($"SC编号{qTScMessagePlcActionBO.EquipmentCode} 作业号{qTScMessagePlcActionBO.ExecutedJobNum} 存在WCS作业，不能执行空闲SC作业");
                                return;
                                //throw new Exception($"SC编号{qTScMessagePlcActionBO.EquipmentCode} 作业号{qTScMessagePlcActionBO.ExecutedJobNum} 没有WCS作业");
                            }
                        }

                        if (await _scGetWMSTaskService.WCSCheckSCHaveExcuecutingTaskWork(qTScMessagePlcActionBO.EquipmentCode) > 0)
                        {
                            _logUtil.Info($"SC编号{qTScMessagePlcActionBO.EquipmentCode} 作业号{qTScMessagePlcActionBO.ExecutedJobNum} 存在WCS作业，不能执行空闲SC作业");
                            return;
                        }

                        //Sc写入Db
                        PlcWriteDbInfo plcWriteDbInfo = await _scGetWMSTaskService.ScGetPlcWriteDbInfoAsync(qTScMessagePlcActionBO.EquipmentCode, "QTScMessageWriteWcsActionBO");
                        //Sc使用Plc连接
                        var plcservice = _plcConnectionPoolService.S7GetWritePlcConnection(plcWriteDbInfo.PlcConnectionId);
                        if (plcservice == null)
                        {
                            throw new Exception($"PLC连接Id:{plcWriteDbInfo.PlcConnectionId}不存在");
                        }

                        //WMS作业
                        var wmstask = await _scGetWMSTaskService.ScGetFirstWorkTaskInfoAsync(qTScMessagePlcActionBO.EquipmentCode, planarStateBOs);
                        if (wmstask.TaskType == EnumTaskType.STA ||
                            wmstask.TaskType == EnumTaskType.AA  ||
                            wmstask.TaskType == EnumTaskType.ATS ||
                            wmstask.TaskType == EnumTaskType.ATA ||
                            wmstask.TaskType == EnumTaskType.STS)
                        {
                            QTScMessageWriteWcsActionBO qTScMessageWriteWcsActionBO = new QTScMessageWriteWcsActionBO();
                            qTScMessageWriteWcsActionBO.ExecutedJobNum = wmstask.TaskCode;
                            qTScMessageWriteWcsActionBO.ForkControl = 1;
                            qTScMessageWriteWcsActionBO.FromRow = Convert.ToInt16(wmstask.CurrentFromCargo.Substring(1, 3)) % 2 == 1 ? (short)1 : (short)2; ;
                            qTScMessageWriteWcsActionBO.FromCol = Convert.ToInt16(wmstask.CurrentFromCargo.Substring(4, 3));
                            qTScMessageWriteWcsActionBO.FromLayer = Convert.ToInt16(wmstask.CurrentFromCargo.Substring(7, 3));
                            qTScMessageWriteWcsActionBO.FromDepth = 1;
                            qTScMessageWriteWcsActionBO.ToRow = Convert.ToInt16(wmstask.CurrentToCargo.Substring(1, 3)) % 2 == 1 ? (short)1 : (short)2; ;
                            qTScMessageWriteWcsActionBO.ToCol = Convert.ToInt16(wmstask.CurrentToCargo.Substring(4, 3));
                            qTScMessageWriteWcsActionBO.ToLayer = Convert.ToInt16(wmstask.CurrentToCargo.Substring(7, 3));
                            qTScMessageWriteWcsActionBO.ToDepth = 1;
                            qTScMessageWriteWcsActionBO.CommandMode = 1;
                            qTScMessageWriteWcsActionBO.SpecialTaskFlag = 1;
                            qTScMessageWriteWcsActionBO.ForkShield = 0;
                            qTScMessageWriteWcsActionBO.CompletionFlag = 1;
                            byte[] wcsBytes = qTScMessageWriteWcsActionBO.Deserialize();
                            bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart, wcsBytes);
                            if (flag)
                            {
                                wmstask.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                                wmstask.CurrentUpdateTime = DateTime.Now;
                                wmstask.TaskState = EnumTaskState.Executing;
                                wmstask.UpdateTime = DateTime.Now;
                                await _scGetWMSTaskService.ScUpdateWorkTaskInfoAsync(wmstask);
                                try
                                {
                                    await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(wmstask.WmsTaskCode, 2, 0);
                                }
                                catch (Exception ex)
                                {
                                    _logUtil.Info($"WCS更新WMS作业号：{wmstask.WmsTaskCode}任务为执行状态失败");
                                }

                                TaskRouteDetailRecordInfo taskRouteDetailRecordInfo = new TaskRouteDetailRecordInfo();
                                taskRouteDetailRecordInfo.TaskID = wmstask.ID;
                                taskRouteDetailRecordInfo.RouteDetailID = wmstask.CurrentRounteDetailID;
                                taskRouteDetailRecordInfo.DetailTaskState = EnumDetailTaskState.Executing;
                                taskRouteDetailRecordInfo.DispatchType = wmstask.CurrentDispatchType;
                                taskRouteDetailRecordInfo.FromEquipment = wmstask.CurrentFromEquipment;
                                taskRouteDetailRecordInfo.FromCargo = wmstask.CurrentFromCargo;
                                taskRouteDetailRecordInfo.ToEquipment = wmstask.CurrentToEquipment;
                                taskRouteDetailRecordInfo.ToCargo = wmstask.CurrentToCargo;
                                taskRouteDetailRecordInfo.CreateTime = wmstask.CurrentCreateTime;
                                taskRouteDetailRecordInfo.UpdateTime = DateTime.Now;
                                await _scGetWMSTaskService.InsertTaskRouteDetailRecordInfoAsync(taskRouteDetailRecordInfo);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logUtil.Info(ex.ToString());
                    }
                }
                #endregion

                #region SC重入上报WCS
                //if (qTScMessagePlcActionBO.OperationMode == 2 &&
                //    qTScMessagePlcActionBO.FaultCode == 3 &&
                //    qTScMessagePlcActionBO.Fork1Status == 1 &&
                //    qTScMessageWcsActionBO.CompletionFlag == 0)
                //{
                //    try
                //    {
                //        var reenter = await _scGetWMSTaskService.ScGetReEnterWorkTaskInfoAsync(qTScMessagePlcActionBO.ExecutedJobNum);
                //        if (reenter == null)
                //        {
                //            throw new Exception($"{qTScMessagePlcActionBO.EquipmentCode} 在重入报警中,WMS在分配新货位");
                //        }
                //        AllotLocationOutputDto allotLocationOutputDto = null;
                //        try
                //        {
                //            allotLocationOutputDto = await WCSMessageWithWMSApi.WCSGetReAllotLocatonAsync(reenter.WmsTaskCode, reenter.WmsToPosition);
                //        }
                //        catch (Exception ex)
                //        {
                //            throw new Exception($"{qTScMessagePlcActionBO.EquipmentCode}货位重分配异常" + ex.ToString());
                //        }
                //        reenter.WmsToPosition = allotLocationOutputDto.LocationCode;
                //        reenter.TaskProcessState = EnumTaskProcessState.ReAllotLocation;
                //        reenter.UpdateTime = DateTime.Now;
                //        reenter.CurrentToCargo = allotLocationOutputDto.LocationCode;
                //        reenter.CurrentUpdateTime = DateTime.Now;
                //        await _scGetWMSTaskService.WcsUpdateReallotLocationAsync(reenter);

                //        byte[] wcsBytes = new byte[1];
                //        HelperByte.SetIntAt(wcsBytes, 22, 7);
                //        //Sc写入Db
                //        PlcWriteDbInfo plcWriteDbInfo = await _scGetWMSTaskService.ScGetPlcWriteDbInfoAsync(qTScMessagePlcActionBO.EquipmentCode, "QTScMessageWriteWcsActionBO");
                //        //Sc使用Plc连接
                //        var plcservice = _plcConnectionPoolService.S7GetWritePlcConnection(plcWriteDbInfo.PlcConnectionId);
                //        if (plcservice == null)
                //        {
                //            throw new Exception($"PLC连接Id:{plcWriteDbInfo.PlcConnectionId}不存在");
                //        }
                //        bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart + 22, wcsBytes);
                //    }
                //    catch (Exception ex)
                //    {
                //        _logUtil.Info(ex.ToString());
                //    }
                //}
                #endregion

                #region  WCS 下发重入作业
                //if (qTScMessagePlcActionBO.OperationMode == 2 &&
                //    qTScMessagePlcActionBO.EquipmentStatus == 2 &&
                //    qTScMessagePlcActionBO.FaultCode == 0 &&
                //    qTScMessagePlcActionBO.ExecutedJobNum == 0 &&
                //    qTScMessagePlcActionBO.Fork1Status == 1 &&
                //    qTScMessageWcsActionBO.CompletionFlag == 0)
                //{
                //    var wmsReallotLocationTask = await _scGetWMSTaskService.ScGetReallotLocationByScEquipmentAsync(qTScMessagePlcActionBO.EquipmentCode);
                //    if (wmsReallotLocationTask == null)
                //    {
                //        throw new Exception($"{qTScMessagePlcActionBO.EquipmentCode} 没有查询到重新分配的作业");
                //    }
                //    //Sc写入Db
                //    PlcWriteDbInfo plcWriteDbInfo = await _scGetWMSTaskService.ScGetPlcWriteDbInfoAsync(qTScMessagePlcActionBO.EquipmentCode, "ZJNScMessageWriteWcsActionBO");
                //    //Sc使用Plc连接
                //    var plcservice = _plcConnectionPoolService.S7GetWritePlcConnection(plcWriteDbInfo.PlcConnectionId);
                //    if (plcservice == null)
                //    {
                //        throw new Exception($"PLC连接Id:{plcWriteDbInfo.PlcConnectionId}不存在");
                //    }

                //    QTScMessageWriteWcsActionBO qTScMessageWriteWcsActionBO = new QTScMessageWriteWcsActionBO();
                //    qTScMessageWriteWcsActionBO.ExecutedJobNum = wmsReallotLocationTask.TaskCode;
                //    qTScMessageWriteWcsActionBO.ForkControl = 1;
                //    qTScMessageWriteWcsActionBO.FromRow = Convert.ToInt16(wmsReallotLocationTask.CurrentFromCargo.Substring(1, 3));
                //    qTScMessageWriteWcsActionBO.FromCol = Convert.ToInt16(wmsReallotLocationTask.CurrentFromCargo.Substring(4, 3));
                //    qTScMessageWriteWcsActionBO.FromLayer = Convert.ToInt16(wmsReallotLocationTask.CurrentFromCargo.Substring(7, 3));
                //    qTScMessageWriteWcsActionBO.FromDepth = 1;
                //    qTScMessageWriteWcsActionBO.ToRow = Convert.ToInt16(wmsReallotLocationTask.CurrentToCargo.Substring(1, 3));
                //    qTScMessageWriteWcsActionBO.ToCol = Convert.ToInt16(wmsReallotLocationTask.CurrentToCargo.Substring(4, 3));
                //    qTScMessageWriteWcsActionBO.ToLayer = Convert.ToInt16(wmsReallotLocationTask.CurrentToCargo.Substring(7, 3));
                //    qTScMessageWriteWcsActionBO.ToDepth = 1;
                //    qTScMessageWriteWcsActionBO.CommandMode = 3;
                //    qTScMessageWriteWcsActionBO.SpecialTaskFlag = 1;
                //    qTScMessageWriteWcsActionBO.ForkShield = 0;
                //    qTScMessageWriteWcsActionBO.CompletionFlag = 1;
                //    byte[] wcsBytes = qTScMessageWriteWcsActionBO.Deserialize();
                //    bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart, wcsBytes);
                //    if (flag)
                //    {
                //        TaskRouteDetailRecordInfo taskRouteDetailRecordInfo = new TaskRouteDetailRecordInfo();
                //        taskRouteDetailRecordInfo.TaskID = wmsReallotLocationTask.ID;
                //        taskRouteDetailRecordInfo.RouteDetailID = wmsReallotLocationTask.CurrentRounteDetailID;
                //        taskRouteDetailRecordInfo.DetailTaskState = EnumDetailTaskState.Executing;
                //        taskRouteDetailRecordInfo.DispatchType = wmsReallotLocationTask.CurrentDispatchType;
                //        taskRouteDetailRecordInfo.FromEquipment = wmsReallotLocationTask.CurrentFromEquipment;
                //        taskRouteDetailRecordInfo.FromCargo = wmsReallotLocationTask.CurrentFromCargo;
                //        taskRouteDetailRecordInfo.ToEquipment = wmsReallotLocationTask.CurrentToEquipment;
                //        taskRouteDetailRecordInfo.ToCargo = wmsReallotLocationTask.CurrentToCargo;
                //        taskRouteDetailRecordInfo.CreateTime = wmsReallotLocationTask.CurrentCreateTime;
                //        taskRouteDetailRecordInfo.UpdateTime = DateTime.Now;
                //        await _scGetWMSTaskService.InsertTaskRouteDetailRecordInfoAsync(taskRouteDetailRecordInfo);
                //    }
                //}
                #endregion

                #region  SC取空
                if (qTScMessagePlcActionBO.OperationMode == 2 &&
                     qTScMessagePlcActionBO.FaultCode == 5 &&
                     qTScMessagePlcActionBO.Fork1Status == 0 &&
                     qTScMessageWcsActionBO.CompletionFlag == 0)
                {
                    try
                    {
                        var takeempty = await _scGetWMSTaskService.ScGetTakeEmptyWorkTaskInfoAsync(qTScMessagePlcActionBO.ExecutedJobNum);
                        if (takeempty == null)
                        {
                            throw new Exception($"{qTScMessagePlcActionBO.EquipmentCode} 在取空报警中,WCS没有对应的作业");
                        }
                        takeempty.TaskState = EnumTaskState.Cancel;
                        takeempty.UpdateTime = DateTime.Now;
                        bool send = false;
                        try
                        {
                            send = await WCSMessageWithWMSApi.WCSNoticeErrorTaskProcessStateAsync(takeempty.WmsTaskCode, takeempty.WmsFromPosition, 5);
                        }
                        catch (Exception ex)
                        {
                            _logUtil.Info($"{takeempty.WmsTaskCode} 上报WMS消息异常," + ex.ToString());
                        }

                        if (send)
                        {
                            takeempty.UploadWmsState = EnumUploadWmsState.Succeed;
                        }
                        else
                        {
                            takeempty.UploadWmsState = EnumUploadWmsState.Failed;
                        }
                        await _scGetWMSTaskService.WcsUpdateTakeEmptyAsync(takeempty);

                        byte[] wcsBytes = new byte[1];
                        HelperByte.SetIntAt(wcsBytes, 22, 7);
                        //Sc写入Db
                        PlcWriteDbInfo plcWriteDbInfo = await _scGetWMSTaskService.ScGetPlcWriteDbInfoAsync(qTScMessagePlcActionBO.EquipmentCode, "QTScMessageWriteWcsActionBO");
                        //Sc使用Plc连接
                        var plcservice = _plcConnectionPoolService.S7GetWritePlcConnection(plcWriteDbInfo.PlcConnectionId);
                        if (plcservice == null)
                        {
                            throw new Exception($"PLC连接Id:{plcWriteDbInfo.PlcConnectionId}不存在");
                        }
                        bool flag = await plcservice.WriteDbAsync(plcWriteDbInfo.DbCode, plcWriteDbInfo.DbStart + 22, wcsBytes);
                    }
                    catch (Exception ex)
                    {
                        _logUtil.Info(ex.ToString());
                    }

                }
                #endregion 

            }
        }


    }
}
